package com.khotyn.heresy.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.khotyn.heresy.bean.HeresyErrorMessage;
import com.khotyn.heresy.exception.IllegalUrlParamException;
import com.khotyn.heresy.service.InformAgainstPictureService;

/**
 * 举报图片控制类
 * 
 * @author 黄挺
 */
@Controller
@RequestMapping("/informAgainstPicture.html")
@SessionAttributes("validateCode")
public class InformAgainstPictureController {
	@Autowired
	InformAgainstPictureService informAgainstPictureService;

	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView onLoad(HttpSession session, HttpServletRequest request,
			@RequestParam(value = "pictureID", required = false) String pictureID,
			@RequestParam(value = "reportPictureValidateCode", required = false) String reportPictureValidateCode,
			@ModelAttribute("validateCode") String validateCode) {
		Integer userID = (Integer) session.getAttribute("userID");

		try {
			validate(pictureID, reportPictureValidateCode, validateCode);
		} catch (IllegalUrlParamException e) {
			return e.getErrorModel();
		}

		informAgainstPictureService.doService(pictureID, userID);
		return new ModelAndView("redirect:/picture.html?pictureID=" + pictureID);
	}

	private void validate(String pictureID, String reportPictureValidateCode, String validateCode) throws IllegalUrlParamException {
		HeresyErrorMessage errorMessage = null;

		if (NumberUtils.isDigits(pictureID)) {
			errorMessage = new HeresyErrorMessage("非法的参数", "操作失败", "picture.html?pictureID=" + pictureID);
		} else if (!validateCode.equals(reportPictureValidateCode.toUpperCase())) {
			errorMessage = new HeresyErrorMessage("验证码错误，请重新填写", "操作失败", "picture.html?pictureID=" + pictureID);
		}

		if (errorMessage != null) {
			throw new IllegalUrlParamException(errorMessage);
		}
	}
}
